package com.itheima.app.interceptor;

import com.itheima.domain.db.User;
import com.itheima.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    //进入controller之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验token
        String token = request.getHeader("Authorization");
        if (token != null) {
            Map<String, Object> map = JwtUtil.parseToken(token);
            if (map != null) {
                //解析成功，将用户信息放入ThreadLocal
                User user = new User();
                user.setId(Long.parseLong(map.get("id").toString()));
                user.setPhone(map.get("phone").toString());
                UserHolder.set(user);
                return true;
            }
        }
        return false;
    }


    //页面渲染完毕之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}


